<template>
    <el-form
        ref="ruleRef"
        :model="state.ruleForm"
        :rules="state.rules"
        label-position="top"
    >
        <el-form-item label="取货员" prop="pickerSid" for="_">
            <el-select
                v-model="state.ruleForm.pickerSid"
                placeholder="请选择取货员"
                clearable
            >
                <el-option
                    v-for="item in state.pickerOptions"
                    :key="item.sid"
                    :label="item.nickName"
                    :value="item.sid"
                />
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button
                type="primary"
                :loading="form_loading"
                class="w-100% mt-10 mb--10"
                @click="submitForm(ruleRef)"
            >
                确认
            </el-button>
        </el-form-item>
    </el-form>
</template>

<script setup>
import { reactive, ref, inject, onMounted } from "vue";
import { getWorkPickers, changeOrderPicker } from "@/apis/order/order";

const emit = defineEmits(["success"]);
const props = defineProps({
    sid: {
        type: String,
        required: true,
    },
    pickerSid: {
        type: String,
        default: null,
    },
});

const $message = inject("$message");

const form_loading = ref(false);
const ruleRef = ref(null);
const state = reactive({
    ruleForm: {
        pickerSid: null,
        orderSid: null,
    },
    rules: {
        pickerSid: [
            { required: true, message: "请选择取货员", trigger: "blur" },
        ],
    },
    pickerOptions: [],
});

onMounted(() => {
    state.ruleForm.pickerSid = props.pickerSid;
    state.ruleForm.orderSid = props.sid;
    pickerOptions();
});

const pickerOptions = async () => {
    const res = await getWorkPickers({
        orderSid: state.ruleForm.orderSid,
    });
    if (res.data.code == 200) {
        state.pickerOptions = res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 修改取货员
const submitForm = (formEl) => {
    if (!formEl) return;
    formEl.validate(async (valid, fields) => {
        if (valid) {
            form_loading.value = true;
            let res = await changeOrderPicker(state.ruleForm);
            form_loading.value = false;
            if (res.data.code == 200) {
                $message({
                    message: "操作成功",
                    type: "success",
                });
                emit("success");
            } else {
                $message({ message: res.data.msg, type: "error" });
            }
        }
    });
};
</script>
